package com.java202411.service.project;


import com.auth0.jwt.JWT;
import com.java202411.contoller.authorization.AuthorizationOfficer;
import com.java202411.contoller.commons.RoleConstant;
import com.java202411.entity.FileEntity;
import com.java202411.entity.UserEntity;
import com.java202411.entity.project.ProjectEntity;
import com.java202411.entity.project.ProjectStatus;
import com.java202411.repository.FileRepository;
import com.java202411.repository.ProjectRepository;
import com.java202411.repository.UserRepository;
import com.java202411.service.commons.NotFoundException;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.hibernate.validator.constraints.Length;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Validated
@RequiredArgsConstructor
public class ProjectService {
    private final ProjectRepository projectRepository;
    private final FileRepository fileRepository;
    private final UserRepository userRepository;

    public ProjectEntity createProject(
            Long userId,
            @NotNull @NotBlank @Length(max = 30) String name,
            @NotNull @NotBlank String description,
            List<Long> fileIds) {

        List<FileEntity> files = fileRepository.findByIds(fileIds);

        ProjectEntity project = ProjectEntity.builder()
                .createdAt(LocalDateTime.now())
                .updatedAt(LocalDateTime.now())
                .name(name)
                .description(description)
                .status(ProjectStatus.Draft)
                .userId(userId)
                .files(files)
                .build();
        return projectRepository.save(project);
    }

    public List<ProjectEntity> queryAllProject() {
        String accessToken = AuthorizationOfficer.getAccessToken();
        String email = JWT.decode(accessToken).getClaim("email").asString();

        UserEntity user = userRepository.findByEmail(email)
                .orElseThrow(() -> new NotFoundException("user not existed: " + email));

        boolean isTeacher = user.getRoles()
                .stream()
                .anyMatch(it -> it.equals(RoleConstant.TEACHER_ROLE));

        List<ProjectStatus> projectStatuses;
        if (isTeacher) {
            projectStatuses = List.of(ProjectStatus.Draft, ProjectStatus.Published);
        } else {
            projectStatuses = List.of(ProjectStatus.Published);
        }

        return projectRepository.findAll(projectStatuses);
    }
}
